package tv.dyndns.kishibe.server.websocket;

import java.io.Closeable;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import org.eclipse.jetty.websocket.WebSocket;

public abstract class BroadcastWebSockets<T> implements Closeable {
	private static class PollingWebSocket implements WebSocket {
		private final Set<PollingWebSocket> broadcast;
		private Connection connection;

		private PollingWebSocket(Set<PollingWebSocket> broadcast) {
			this.broadcast = broadcast;
		}

		@Override
		public void onOpen(Connection connection) {
			this.connection = connection;
			broadcast.add(this);
		}

		@Override
		public void onClose(int closeCode, String message) {
			broadcast.remove(this);
		}

		public void sendMessage(String data) throws IOException {
			connection.sendMessage(data);
		}
	}

	private final Set<PollingWebSocket> broadcast = new CopyOnWriteArraySet<PollingWebSocket>();

	public void send(T data) {
		String json = parse(data);
		for (PollingWebSocket webSocket : broadcast) {
			try {
				webSocket.sendMessage(json);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void close() {
		for (PollingWebSocket webSocket : broadcast) {
			webSocket.connection.close();
		}
		broadcast.clear();
	}

	protected abstract String parse(T data);

	public WebSocket newWebSocket() {
		return new PollingWebSocket(broadcast);
	}
}
